package com.example.chapter06;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;

import androidx.appcompat.app.AppCompatActivity;

public class shareWriteActivity extends AppCompatActivity implements View.OnClickListener, RadioGroup.OnCheckedChangeListener {

    private EditText et_name;
    private EditText et_age;
    private EditText et_height;
    private EditText et_weight;
    private int marriage;
    private RadioGroup rg_marriage;

    private SharedPreferences preferences;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share_write);

        et_name = findViewById(R.id.et_name);
        et_age = findViewById(R.id.et_age);
        et_height = findViewById(R.id.et_height);
        et_weight = findViewById(R.id.et_weight);
        rg_marriage = findViewById(R.id.rg_marriage);
        rg_marriage.setOnCheckedChangeListener(this);

        findViewById(R.id.logon).setOnClickListener(this);

        preferences = getSharedPreferences("config", Context.MODE_PRIVATE);
        reload();
    }

    private void reload() {
        String name = preferences.getString("name", null);
        if (name != null) {
            et_name.setText(name);
        }
        int age = preferences.getInt("age", 0);
        if (age != 0) {
            et_age.setText(String.valueOf(age));
        }
        float height = preferences.getFloat("height", 0f);
        if (height != 0f) {
            et_height.setText(String.valueOf(height));
        }
        float weight = preferences.getFloat("weight", 0f);
        if (weight != 0f) {
            et_weight.setText(String.valueOf(weight));
        }
        int marriage = preferences.getInt("marriage", 0);
        if (marriage != 0) {
            rg_marriage.check(marriage);
        }
    }

    @Override
    public void onClick(View view) {
        String name = et_name.getText().toString();
        String age = et_age.getText().toString();
        String height = et_height.getText().toString();
        String weight = et_weight.getText().toString();
        System.out.println(name);
        System.out.println(age);
        System.out.println(height);
        System.out.println(weight);
        System.out.println(marriage);

        final SharedPreferences.Editor edit = preferences.edit();
        edit.putString("name", name);
        edit.putInt("age", Integer.parseInt(age));
        edit.putFloat("height", Float.parseFloat(height));
        edit.putFloat("weight", Float.parseFloat(weight));
        edit.putInt("marriage", marriage);
        edit.apply();
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        marriage=i;
    }
}